<template>
    <div>
        <el-form
            class="form-inline"
            ref="formRef"
            :model="formData"
            label-width="100px"
            :rules="rules"
            status-icon
            :inline="true"
        >
            <el-row>
                <el-col :span="6">
                    <el-form-item label="客户" prop="fee_unit_cod">
                        <el-select
                            v-model="formData.fee_unit_cod"
                            filterable
                            placeholder="Select"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in client"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="收付款" prop="fee_in_out">
                        <el-select
                            v-model="formData.fee_in_out"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in SelectOptionFeeInOut"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="成本中心" prop="fee_owner">
                        <el-select
                            v-model="formData.fee_owner"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in cntrOwner"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="5">
                    <el-form-item label="汇率" prop="rate">
                        <el-input-number
                            v-model="formData.rate"
                        ></el-input-number>
                    </el-form-item>
                </el-col> -->
                <el-col :span="6">
                    <el-button type="primary" @click="onRefresh" size="default"
                        >刷新</el-button
                    >
                    <el-button
                        type="primary"
                        @click="onNormalAudit"
                        size="default"
                        >核销</el-button
                    >
                    <el-button
                        type="primary"
                        @click="onForceAudit"
                        size="default"
                        >强制核销</el-button
                    >
                </el-col>
            </el-row>
        </el-form>
    </div>
    <div>
        <el-table
            ref="payTableRef"
            :data="payTableData"
            v-bind="tableDefaultAttribute"
            row-key="id"
            :max-height="250"
            table-layout="auto"
        >
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column type="selection" width="55" :align="'center'" />
            <template v-for="col in payTableColumns" :key="col.prop">
                <el-table-column
                    v-if="!col.isHidden"
                    :align="col.align"
                    :prop="col.prop"
                    :label="col.label"
                    :fixed="col.fixed"
                    :formatter="col.formatter"
                    :type="col.type"
                    :width="col.width"
                >
                    <template
                        v-if="col.formFieldItemType === 'boolean'"
                        #default="scope"
                    >
                        <el-switch
                            v-model="scope.row[`${col.prop}`]"
                            :active-value="'Y'"
                            :inactive-value="'N'"
                        />
                    </template>
                </el-table-column>
            </template>
        </el-table>
    </div>
    <div>
        <el-table
            ref="feedetTableRef"
            :data="feedetTableData"
            v-bind="tableDefaultAttribute"
            row-key="id"
            :max-height="450"
            table-layout="auto"
        >
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column type="selection" width="55" :align="'center'" />
            <template v-for="col in feedetTableColumns" :key="col.prop">
                <el-table-column
                    v-if="!col.isHidden"
                    :align="col.align"
                    :prop="col.prop"
                    :label="col.label"
                    :fixed="col.fixed"
                    :formatter="col.formatter"
                    :type="col.type"
                    :width="col.width"
                >
                    <template
                        v-if="col.formFieldItemType === 'boolean'"
                        #default="scope"
                    >
                        <el-switch
                            v-model="scope.row[`${col.prop}`]"
                            :active-value="'Y'"
                            :inactive-value="'N'"
                        />
                    </template>
                </el-table-column>
            </template>
        </el-table>
    </div>
    <el-dialog
        v-model="dialogShowResultVisible"
        title="核销结果"
        draggable
        destroy-on-close
    >
        <AuditResult :result="paramData" @close="onCloseDialog"></AuditResult>
    </el-dialog>
    <el-dialog v-model="dialogForceRemarkVisible" draggable destroy-on-close>
        <ForceRemark @close="onCloseDialog" @update="onUpdate"></ForceRemark>
    </el-dialog>
</template>
<script setup lang="ts" name="FeeAudit">
import { ElMessage, FormInstance, FormRules, TableRefs } from 'element-plus';
import { ref, reactive } from 'vue';
import { storeToRefs } from 'pinia';
import { useAppStore } from '@/store/app';
import {
    AuditFeedetModel,
    AuditPayModel,
    
} from '@/common/types/business';
import { TableColumn } from '@/common/types/app';
import { tableColumnDefault } from '@/hooks/useTable';
import { formatDate, transFormatter } from '@/common/tools';
import { tableDefaultAttribute } from '@/hooks/useTable';
import { Request } from '@/app/request';
import { forEach, isEmpty } from 'lodash';
import { ValidateFieldsError } from 'async-validator';
import AuditResult from './AuditResult.vue';
import ForceRemark from './ForceRemark.vue';
type filterForm = {
    fee_unit_cod?: string;
    fee_owner?: number;
    fee_in_out?: string;
    force_audit?: string;
    audit_remark?: string;
    // rate?: number;
};
const formRef = ref<FormInstance>();
const formData = reactive<filterForm>({});
const payTableRef = ref<TableRefs>();
const payTableData = ref<AuditPayModel[]>([]);
const feedetTableRef = ref<TableRefs>();
const feedetTableData = ref<AuditFeedetModel[]>([]);
const dialogShowResultVisible = ref(false);
const dialogForceRemarkVisible = ref(false);
const paramData = ref<any>();
const rules = reactive<FormRules>({
    fee_unit_cod: [{ required: true, message: '请选择客户', trigger: 'blur' }],
    fee_in_out: [{ required: true, message: '请选择收付款', trigger: 'blur' }],
    fee_owner: [{ required: true, message: '请选择成本中心', trigger: 'blur' }],
});
const {
    client,
    currency,
    category,
    SelectOptionYN,
    SelectOptionFeeInOut,
    
    feecod,
    cyCfs,
    cntrOwner,
} = storeToRefs(useAppStore());
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'currency_cod') {
        data = currency.value;
    } else if (column['property'] === 'fee_unit_cod') {
        data = client.value;
    } else if (column['property'] === 'pay_typ') {
        data = category.value;
    } else if (
        ['audit_finish_id', 'special_id', 'need_audit', 'audit_id'].includes(
            column['property'],
        )
    ) {
        data = SelectOptionYN.value;
    } else if (column['property'] === 'i_o_id') {
        data = SelectOptionFeeInOut.value;
    } else if (column['property'] === 'cfs_cod') {
        data = cyCfs.value;
    } else if (column['property'] === 'fee_cod') {
        data = feecod.value;
    } else if (column['property'] === 'fee_owner') {
        data = cntrOwner.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const payTableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 4,
        prop: 'fee_tim',
        label: '付款日期',
        fixed: 'left',
        formatter: formatDate,
        sortable: 'custom',
        formFieldItemType: 'date',
        width: 200,
    },
    /* {
        ...tableColumnDefault,
        order: 5,
        prop: 'pay_typ',
        label: '资金账号',
        formatter: onFormatter,
        fixed: 'left',
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: category,
        width: 200
    }, */
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'currency_cod',
        label: '货币',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: currency.value,
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'amount',

        label: '金额',
        sortable: 'custom',
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'unaudit_amount',

        label: '未核销金额',
        sortable: 'custom',
        width: 150,
    },
    /* {
        ...tableColumnDefault,
        order: 6,
        prop: 'i_o_id',
        label: '付款类型',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: SelectOptionFeeInOut,
        width: 120
    }, 
    {
        ...tableColumnDefault,
        order: 12,
        prop: 'fee_owner',
        label: '成本中心',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: cntrOwner,
        width: 150
    },*/
    

    {
        ...tableColumnDefault,
        order: 8,
        prop: 'pay_no',
        label: '付款码',
        sortable: 'custom',
        formFieldItemType: 'input',
        width: 150,
    },

    /* {
        ...tableColumnDefault,
        order: 10,
        prop: 'need_audit',
        label: '需要核销',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN,
        width: 100
    }, 
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'cfs_cod',
        label: '站点',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: cyCfs,
        width: 150
    },*/

    /*{
        ...tableColumnDefault,
        order: 13,
        prop: 'fee_bill_no',
        label: '账单号',
        sortable: 'custom',
        formFieldItemType: 'input',
        width: 150,
    },
     {
        ...tableColumnDefault,
        order: 7,
        prop: 'audit_finish_id',
        label: '核销完成',
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN,
        noFormField: true,
        width: 80
    }, */
    {
        ...tableColumnDefault,
        order: 14,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
        width: 200,
    },
]);
const feedetTableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'currency_cod',
        label: '货币',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: currency.value,
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'amount',

        label: '金额',
        sortable: 'custom',
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'unaudit_amount',

        label: '未核销金额',
        sortable: 'custom',
        width: 150,
    },

    
    {
        ...tableColumnDefault,
        order: 12,
        prop: 'fee_cod',
        label: '费目',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: feecod.value,
        width: 120,
    },

    {
        ...tableColumnDefault,
        order: 11,
        prop: 'cfs_cod',
        label: '站点',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: cyCfs.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 14,
        prop: 'cntr',
        label: '箱号',
        sortable: 'custom',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 14,
        prop: 'cntr_siz_cod',
        label: '尺寸',
        sortable: 'custom',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 14,
        prop: 'cntr_cntr_typ',
        label: '箱型',
        sortable: 'custom',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 14,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
        width: 200,
    },
]);
const onRefresh = async () => {
    const formValid = await formRef.value?.validate(
        (isValid: boolean, _invalidFields?: ValidateFieldsError) => {
            // return isValid;
        },
    );
    if (formValid) {
        const req = new Request('核销实收付应收付查询', {
            where: {
                fee_unit_cod: {
                    equals: formData.fee_unit_cod,
                },
                fee_owner: {
                    equals: formData.fee_owner,
                },
                fee_in_out: {
                    equals: formData.fee_in_out,
                },
            },
        });
        const r = await req.post();

        payTableData.value.length = 0;
        feedetTableData.value.length = 0;
        if (r.obj) {
            payTableData.value = r.obj;
            feedetTableData.value = r.ext;
        }
    }
};
const onForceAudit = async () => {
    formData.force_audit = 'Y';
    dialogForceRemarkVisible.value = true;
};
const onNormalAudit = async () => {
    formData.force_audit = 'N';
    await onAudit();
};
const onAudit = async () => {
    // dialogShowResultVisible.value = true;
    const payids = Array<number>();
    const feedetids = Array<number>();
    const payrows: Array<AuditPayModel> = payTableRef.value?.getSelectionRows();
    if (payrows.length === 0) {
        ElMessage.info({
            message: '请选择要核销数据',
        });
        return;
    }
    forEach(payrows, (v: AuditPayModel) => {
        payids.push(v.id as number);
    });
    const feedetrows: Array<AuditFeedetModel> =
        feedetTableRef.value?.getSelectionRows();
    if (feedetrows.length === 0) {
        ElMessage.info({
            message: '请选择要核销数据',
        });
        return;
    }
    forEach(feedetrows, (v: AuditFeedetModel) => {
        feedetids.push(v.id as number);
    });
    if (formData.force_audit === 'Y' && !formData.audit_remark) {
        ElMessage.info({
            message: '强制核销必须输入备注',
        });
        return;
    }
    const req = new Request('核销', {
        payids,
        feedetids,
        ...formData,
    });
    const r = await req.post();

    if (r.code > 100) {
        dialogShowResultVisible.value = true;
        paramData.value = r.obj;
        onRefresh();
    }
};
const onUpdate = async (remark: string) => {
    dialogForceRemarkVisible.value = false;
    formData.force_audit = 'Y';
    formData.audit_remark = remark;
    await onAudit();
};
const onCloseDialog = async (arg?: any) => {
    if (dialogShowResultVisible.value) {
        dialogShowResultVisible.value = false;
    }
    if (dialogForceRemarkVisible.value) {
        dialogForceRemarkVisible.value = false;
    }
};
</script>
<style lang="scss" scoped>
.form-inline .el-input {
    --el-input-width: 220px;
}

.form-inline .el-select {
    --el-select-width: 220px;
}
</style>
